class CulturalHeritage::TransfersController < ApplicationController
  before_filter :authenticate_user!
  # GET /cultural_heritage/transfers
  # GET /cultural_heritage/transfers.xml
  def index

     if (user_signed_in? && ([4].include?(current_user.role)))
    
    @title_view = 'Traslados'
    @heritages = CulturalHeritage::CulturalHeritage.all
    @origins = CulturalHeritage::CulturalInstitution.all
    @destinies = CulturalHeritage::CulturalInstitution.all

    if params[:cultural] == nil

      @cultural_heritage_transfers = CulturalHeritage::Transfer.all
    else

      @cultural_heritage = CulturalHeritage::CulturalHeritage.where("name LIKE '%#{params[:cultural][:cultural_heritage]}%'")


      @cultural_heritage_transfers = CulturalHeritage::Transfer.where( 'cultural_heritage in (?)', (@cultural_heritage.empty? ? '' : @cultural_heritage.map(&:id)) ).all

    end

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @cultural_heritage_transfers }
    end
    else 
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  # GET /cultural_heritage/transfers/1
  # GET /cultural_heritage/transfers/1.xml



  def show

    if (user_signed_in? && ([4].include?(current_user.role)))

    @title_view = 'Traslados'
    @cultural_heritage_transfer = CulturalHeritage::Transfer.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @cultural_heritage_transfer }
    end

      else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end

  end

  # GET /cultural_heritage/transfers/new
  # GET /cultural_heritage/transfers/new.xml
  def new

    if (user_signed_in? && ([4].include?(current_user.role)))

    @title_view = 'Traslados'
    @cultural_heritage_transfer = CulturalHeritage::Transfer.new
    @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:group=>[1],:deleted=>[0]})
    @heritages = CulturalHeritage::CulturalHeritage.all
    @origins = CulturalHeritage::CulturalInstitution.all
    @destinies = CulturalHeritage::CulturalInstitution.all
    @responsable = User.find_all_by_role(1)
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @cultural_heritage_transfer }
    end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  # GET /cultural_heritage/transfers/1/edit
  def edit
    if (user_signed_in? && ([4].include?(current_user.role)))
    @title_view = 'Traslados'
    @cultural_heritage_transfer = CulturalHeritage::Transfer.find(params[:id])
        else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  # POST /cultural_heritage/transfers
  # POST /cultural_heritage/transfers.xml
  def create
    if (user_signed_in? && ([4].include?(current_user.role)))
      @title_view = 'Traslados'
      aux = params[:cultural_heritage_transfer][:enddate]
      @cultural_heritage_transfer = CulturalHeritage::Transfer.new(params[:cultural_heritage_transfer])
      @cultural_heritage_transfer.creator = current_user.id

      if (aux.nil? || aux.blank?)
        aux = Time.now.strftime("%d/%m/%Y").to_s
      end

      @cultural_heritage_transfer.enddate = DateTime.strptime(aux, "%d/%m/%Y")
      TransferMailer.registered_email(@cultural_heritage_transfer.obj_responsable).deliver

      #harcode par evitar problemas con el nil del id de petrimonio incluido en la tabla transfer
      @cultural_heritage_transfer.cultural_heritage = 1
      
      @heritages = params[:lheritage]
      i = 0

      @heritages.each do |theritage|
        heritagextransfer = CulturalHeritage::MyHeritageXTransfer.new([:transfer => @cultural_heritage_transfer.id])
        heritagextransfer.heritage = theritage.to_i
        @cultural_heritage_transfer.list_heritage_x_transfer << heritagextransfer
        i = i +1
      end

      is_equal_cultural_institution = (@cultural_heritage_transfer.obj_cultural_institution_origin.id == @cultural_heritage_transfer.obj_cultural_institution_destiny.id)
      is_valid_dates = (@cultural_heritage_transfer.startdate <=  DateTime.strptime(aux, "%d/%m/%y"))

      respond_to do |format|
        if (is_equal_cultural_institution)
          @errorTransInsti = "Las instituciones de origen y destino deben ser diferentes."
        end
        if (!is_valid_dates)
          @errorTransDate = "La fecha de inicio debe ser menor a la de fin."
        end
        if (!is_equal_cultural_institution && is_valid_dates)
          if @cultural_heritage_transfer.save

            format.html { redirect_to(@cultural_heritage_transfer, :notice => 'El traslado fue registrado satisfactoriamente.')}
            format.xml  { render :xml => @cultural_heritage_transfer, :status => :created, :location => @cultural_heritage_transfer }

          else
            format.html { render :action => "new"}
            format.xml  { render :xml => @cultural_heritage_transfer.errors, :status => :unprocessable_entity }
          end
        else
          @title_view = 'Traslados'
          @cultural_heritage_transfer = CulturalHeritage::Transfer.new
          @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.all
          @heritages = CulturalHeritage::CulturalHeritage.all
          @origins = CulturalHeritage::CulturalInstitution.all
          @destinies = CulturalHeritage::CulturalInstitution.all
          @responsable = User.find_all_by_role(1)          
          format.html { render :action => "new"}
          format.xml  { render :xml => @cultural_heritage_transfer.errors, :status => :unprocessable_entity }
        end
      end
      else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  # PUT /cultural_heritage/transfers/1
  # PUT /cultural_heritage/transfers/1.xml
  def update

    if (user_signed_in? && ([4].include?(current_user.role)))
    @title_view = 'Traslados'
    @cultural_heritage_transfer = CulturalHeritage::Transfer.find(params[:id])

    respond_to do |format|
      if @cultural_heritage_transfer.update_attributes(params[:cultural_heritage_transfer])
        format.html { redirect_to(@cultural_heritage_transfer, :notice => 'Transfer was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @cultural_heritage_transfer.errors, :status => :unprocessable_entity }
      end
    end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  # DELETE /cultural_heritage/transfers/1
  # DELETE /cultural_heritage/transfers/1.xml
  def destroy
    if (user_signed_in? && ([4].include?(current_user.role)))
    @title_view = 'Traslados'
    @cultural_heritage_transfer = CulturalHeritage::Transfer.find(params[:id])
    @cultural_heritage_transfer.destroy

    respond_to do |format|
      format.html { redirect_to(cultural_heritage_transfers_url) }
      format.xml  { head :ok }
    end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def transfer_state
    if (user_signed_in? && ([4].include?(current_user.role)))
    @title_view = 'Traslados'
    @transfer = CulturalHeritage::Transfer.find(params[:id])
    @transfer.state=1

    @transfer.save
    TransferMailer.in_transfer_email(@transfer.obj_responsable).deliver
    respond_to do |format|
      format.html { redirect_to(cultural_heritage_transfers_url) }
      format.xml  { head :ok }
    end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def finalize_state

    if (user_signed_in? && ([4].include?(current_user.role)))
    @title_view = 'Traslados'
    @transfer = CulturalHeritage::Transfer.find(params[:id])
    @transfer.state=2

    @transfer.list_heritage_x_transfer.each do |theritage|
      @cultural_heritage_aux = CulturalHeritage::CulturalHeritage.find(theritage.heritage)
      @cultural_heritage_aux.typeCulturalInstitution = 1
      @cultural_heritage_aux.culturalInstitution = @transfer.obj_cultural_institution_destiny.id
      @cultural_heritage_aux.save
    end

    @transfer.save
    
    TransferMailer.recibed_email(@transfer.obj_creator).deliver


    respond_to do |format|
      format.html { redirect_to(cultural_heritage_transfers_url) }
      format.xml  { head :ok }
    end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def search
    if (user_signed_in? && ([4].include?(current_user.role)))
    @title_view = 'Traslados'
    @cultural_heritages = CulturalHeritage::CulturalHeritage.all
    #    @transfer = CulturalHeritage::Transfer.find(params[:id])
    #    @transfer.state=2
    #    @transfer.save
    #    respond_to do |format|
    #      format.html { redirect_to(cultural_heritage_transfers_url) }
    #      format.xml  { head :ok }
    #    end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def update_table
    if (user_signed_in? && ([4].include?(current_user.role)))
    @title_view = 'Traslados'
    @heritage_name = params[:heritage_name]
    @origin_place = params[:origin_place]
    @destiny_place = params[:destiny_place]
    @cultural_heritage_transfers = CulturalHeritage::Transfer.all

    if ! @heritage_name.blank?
      if ! @origin_place.blank?
        if ! @destiny_place.blank?
          @cultural_heritage_transfers = CulturalHeritage::Transfer.find(:all,:conditions=>["cultural_heritage_transfers.cultural_heritage = ? and cultural_heritage_transfers.origin = ? and cultural_heritage_transfers.destiny = ? ",@heritage_name,@origin_place,@destiny_place])
        else
          @cultural_heritage_transfers = CulturalHeritage::Transfer.find(:all,:conditions=>["cultural_heritage_transfers.cultural_heritage = ? and cultural_heritage_transfers.origin = ? ",@heritage_name,@origin_place])
        end
      else
        if ! @destiny_place.blank?
          @cultural_heritage_transfers = CulturalHeritage::Transfer.find(:all,:conditions=>["cultural_heritage_transfers.cultural_heritage = ? and cultural_heritage_transfers.destiny = ? ",@heritage_name,@destiny_place])
        else
          @cultural_heritage_transfers = CulturalHeritage::Transfer.find(:all,:conditions=>["cultural_heritage_transfers.cultural_heritage = ? ",@heritage_name])
        end
      end
    else
      if ! @origin_place.blank?
        if ! @destiny_place.blank?
          @cultural_heritage_transfers = CulturalHeritage::Transfer.find(:all,:conditions=>["cultural_heritage_transfers.origin = ? and cultural_heritage_transfers.destiny = ? ",@origin_place,@destiny_place])
        else
          @cultural_heritage_transfers = CulturalHeritage::Transfer.find(:all,:conditions=>["cultural_heritage_transfers.origin = ? ",@origin_place])
        end
      else
        if ! @destiny_place.blank?
          @cultural_heritage_transfers = CulturalHeritage::Transfer.find(:all,:conditions=>["cultural_heritage_transfers.destiny = ? ",@destiny_place])

        end
      end
    end
    render :partial => "table"
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def update_table_heritage

    if (user_signed_in? && ([4].include?(current_user.role)))
    @search_name = params[:search_name]
    @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:group=>[1],:deleted=>[0]})
    if ! @search_name.blank?
      #      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["cultural_heritage_cultural_heritages.group = ? and (cultural_heritage_cultural_heritages.name LIKE ? or cultural_heritage_cultural_heritages.description LIKE ? or cultural_heritage_cultural_heritages.materials LIKE ?)",2,'%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%'])
      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["cultural_heritage_cultural_heritages.group = ? and (cultural_heritage_cultural_heritages.name LIKE ? or cultural_heritage_cultural_heritages.description LIKE ? or cultural_heritage_cultural_heritages.materials LIKE ? or cultural_heritage_cultural_heritages.nationalRegistrationCode LIKE ?)",1,'%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%'])
    else
      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:group=>[1],:deleted=>[0]})
    end
    render :partial => "table_1"
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end
  
end




